//! 响应构建器模块
//! 使用构建器模式简化ISO8583响应消息的构建

use iso8583_rs::iso8583::iso_spec::{IsoMsg, new_msg};
use iso8583_rs::iso8583::IsoError;
use log::debug;
use crate::config::{field_numbers, business_rules, ECHO_FIELDS};

/// 响应消息构建器
pub struct ResponseBuilder<'a> {
    response_msg: IsoMsg,
    request_msg: &'a IsoMsg,
}

impl<'a> ResponseBuilder<'a> {
    /// 创建新的响应构建器
    pub fn new(request_msg: &'a IsoMsg, response_msg_type: &str) -> Result<Self, IsoError> {
        let mut response_msg = new_msg(
            &request_msg.spec,
            request_msg.spec.get_message_from_header(response_msg_type)?.clone()
        );
        
        response_msg.set("message_type", response_msg_type)?;
        
        Ok(Self {
            response_msg,
            request_msg,
        })
    }

    /// 设置响应码
    pub fn with_response_code(mut self, code: &str) -> Result<Self, IsoError> {
        self.response_msg.set_on(39, code)?;
        Ok(self)
    }

    /// 设置批准码（仅在批准时）
    pub fn with_approval_code_if_approved(mut self) -> Result<Self, IsoError> {
        if let Ok(response_code) = self.response_msg.get_field_value(&field_numbers::RESPONSE_CODE.to_string()) {
            if response_code == "000" {
                self.response_msg.set_on(field_numbers::APPROVAL_CODE as u32, business_rules::APPROVAL_CODE)?;
            }
        }
        Ok(self)
    }

    /// 处理附加数据字段（添加后缀）
    pub fn with_additional_data_processing(mut self) -> Result<Self, IsoError> {
        // 处理字段61
        if let Ok(mut val) = self.request_msg.get_field_value(&field_numbers::ADDITIONAL_DATA_1.to_string()) {
            if !val.ends_with(business_rules::ADDITIONAL_DATA_SUFFIX) {
                val.push_str(business_rules::ADDITIONAL_DATA_SUFFIX);
                self.response_msg.set_on(field_numbers::ADDITIONAL_DATA_1 as u32, &val)?;
            }
        }

        // 处理字段62
        if let Ok(mut val) = self.request_msg.get_field_value(&field_numbers::ADDITIONAL_DATA_2.to_string()) {
            if !val.ends_with(business_rules::ADDITIONAL_DATA_SUFFIX) {
                val.push_str(business_rules::ADDITIONAL_DATA_SUFFIX);
                self.response_msg.set_on(field_numbers::ADDITIONAL_DATA_2 as u32, &val)?;
            }
        }

        Ok(self)
    }

    /// 设置默认字段
    pub fn with_default_fields(mut self) -> Result<Self, IsoError> {
        self.response_msg.set_on(field_numbers::ADDITIONAL_DATA_3 as u32, business_rules::DEFAULT_ADDITIONAL_DATA_3)?;
        self.response_msg.set_on(field_numbers::PRIVATE_DATA as u32, business_rules::DEFAULT_PRIVATE_DATA)?;
        Ok(self)
    }

    /// 回显请求字段
    pub fn with_echo_fields(mut self) -> Result<Self, IsoError> {
        for field_num in ECHO_FIELDS {
            if let Ok(value) = self.request_msg.get_field_value(&field_num.to_string()) {
                self.response_msg.set_on(*field_num as u32, &value)?;
            }
        }
        Ok(self)
    }

    /// 设置位图
    pub fn with_bitmap(mut self) -> Self {
        self.response_msg.fd_map.insert("bitmap".to_string(), self.response_msg.bmp.as_vec());
        self
    }

    /// 构建最终的响应消息
    pub fn build(self) -> IsoMsg {
        debug!("响应消息构建完成");
        self.response_msg
    }
}

/// 快速构建器方法
impl<'a> ResponseBuilder<'a> {
    /// 构建标准的成功响应
    pub fn build_success_response(request_msg: &'a IsoMsg, response_msg_type: &str) -> Result<IsoMsg, IsoError> {
        Ok(Self::new(request_msg, response_msg_type)?
            .with_response_code("000")?
            .with_approval_code_if_approved()?
            .with_additional_data_processing()?
            .with_default_fields()?
            .with_echo_fields()?
            .with_bitmap()
            .build())
    }

    /// 构建错误响应
    pub fn build_error_response(request_msg: &'a IsoMsg, response_msg_type: &str, error_code: &str) -> Result<IsoMsg, IsoError> {
        Ok(Self::new(request_msg, response_msg_type)?
            .with_response_code(error_code)?
            .with_echo_fields()?
            .with_bitmap()
            .build())
    }

    /// 构建基于金额的响应
    pub fn build_amount_based_response(request_msg: &'a IsoMsg, response_msg_type: &str, amount: u32) -> Result<IsoMsg, IsoError> {
        let response_code = if amount < business_rules::AMOUNT_THRESHOLD {
            "000"
        } else {
            "100"
        };

        Ok(Self::new(request_msg, response_msg_type)?
            .with_response_code(response_code)?
            .with_approval_code_if_approved()?
            .with_additional_data_processing()?
            .with_default_fields()?
            .with_echo_fields()?
            .with_bitmap()
            .build())
    }
}